package com.gill.touka.sentinel.page;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * sentinel扩展：自定义sentinel异常返回信息
 * 测试方法：
 * 1、访问：localhost:8082/shares/1
 * 2、对shares/1设置流控、降级规则，进行测试
 */
@Component
public class MyUrlBlockHandler implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {

        Msg msg = null;

        if(e instanceof FlowException){
            msg = new Msg().builder()
                    .code(100)
                    .msg("Flow：流控规则生效")
                    .build();
        }
        else if(e instanceof ParamFlowException){
            msg = new Msg().builder()
                    .code(101)
                    .msg("ParamFlow：热点参数规则生效")
                    .build();
        }
        else if(e instanceof DegradeException){
            msg = new Msg().builder()
                    .code(102)
                    .msg("Degrade：降级规则生效")
                    .build();
        }
        else if(e instanceof AuthorityException){
            msg = new Msg().builder()
                    .code(103)
                    .msg("Authority：授权规则生效")
                    .build();
        }
        else if(e instanceof SystemBlockException){
            msg = new Msg().builder()
                    .code(104)
                    .msg("System：系统规则生效")
                    .build();
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type","application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(response.getWriter(),msg);
    }
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class Msg{
    private Integer code;
    private String msg;
}